package org.su.webadapter.velocity;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 处理格式转换问题
 * 
 * @author yangchuan 日期：2009.7.27 修改人：
 * 
 */
public class VelocityUtils {

	protected static final Log logger = LogFactory
	.getLog(VelocityUtils.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	static class SingletonHolder {
		static VelocityUtils instance = new VelocityUtils();
	}

	public static VelocityUtils getInstance() {
		return SingletonHolder.instance;
	}

	/**
	 * 格式化日期数据
	 * 
	 * @param date
	 *            需格式化的日期数据
	 * @return 返回一条被格式化的数据
	 */
	public static String getDate(Date date) {
		if (null == date)
			return null;
		return dateFormat.format(date);
	}

	public static String encode(String str) {
		if (null == str)
			return null;
		try {
			return URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;

	}

	/**
	 * 从类里的某个静态属性中获取指定的key值所对应于的数据， 比如：com.zds.cqcdc.XXX.map;
	 * 如果该map中的值为：{name:'yangchuan'};
	 * 那么获取yangchuan这个数据可以这样：$!Velocity.getMapValue
	 * ("com.zds.cqcdc.XXX.map","name");
	 * 
	 * @param mapPath
	 *            静态类
	 * @param key
	 *            对应的map的key
	 * @return
	 * @throws Exception
	 */
	public static String getMapValue(String mapPath, String key)
			throws Exception {
		String value = "";

		Class<?> clazz = Class.forName(mapPath.substring(0, mapPath
                .lastIndexOf(".")));
		Field field = clazz.getField(mapPath
				.substring(mapPath.lastIndexOf(".") + 1));

		Class<?> mapClass = field.getType();
		Object map = field.get(null);

		Method m = mapClass.getMethod("get", Object.class);

		value = (String) m.invoke(map, key);

		return value;
	}

	/**
	 * 将转义过的html代码还原
	 * 
	 * @param src
	 * @return
	 */
	public static String unescapeHtml(String src) {
		return StringEscapeUtils.unescapeHtml(src);
	}

	/**
	 * 转义html代码
	 * 
	 * @param src
	 * @return
	 */
	public static String escapeHtml(String src) {
		return StringEscapeUtils.escapeHtml(src);
	}

	/**
	 * 获取指定长度的字符串（包括汉字长度的处理）
	 * 
	 * @param value
	 *            源字符串
	 * @param length
	 *            自定长度
	 * @return 返回一个指定长度的字符串
	 */
	public static String showText(String value, int length) {
		return showText(value,length,"...");
	}
	
	public static String showText(String value, int length,String suff) {
		if(StringUtils.isEmpty(value)){
			return value;
		}
		int valueLen = value.length();
		if (StringUtils.isNotEmpty(value) && valueLen > length) {
			int size = length * 2;
			for (int i = 0, count = 0; i < valueLen; i++) {
				char ch = value.charAt(i);

				if (ch >= 0 && ch < 256) {
					count++;
				} else {
					count += 2;
				}

				if (count > size) {
					value = value.substring(0, i) ;
					if(StringUtils.isNotEmpty(suff)){
						value =value + suff;
					}
					break;
				}
			}
		}
		return value;
	}
	
	/**
	 * 显示固定长度字符串
	 * @param value
	 * @param length
	 * @return
	 */
	public static String showFixedText(String value, int length) {
		return showText(value,length,null);
	}
	
	public static String showFilterText(String value, int length)  {
		String result = null;
		if (StringUtils.isNotEmpty(value)) {
			result = HtmlProcessor.htmlToPlainText(value);
		}
		return showText (result,length,"");
	}
	
	public static Object get(Object[]objects, int index){
		return objects[index];
	}
	
	public static void main(String[] args) {
		System.out.println(showFilterText("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><title>dddd</title><script>alert('ss')</script> </head><body>中国<b>123</b>456 <script>alert('ss')</script>ff ee</body></html>fadfadfads", 4));
		
		System.out.println(showText("中国33333123456", 4));
		System.out.println('　'/1);
	}
}
